from config import config
import pickle
import os


def is_supported_file(filename: str) -> bool:
    return any(filename.lower().endswith(ext) for ext in config.SUPPORTED_FORMATS)


def save_document_info(doc_id, doc_text):
    stored_docs = {}
    if os.path.exists(config.DOCUMENT_PKL):
        with open(config.DOCUMENT_PKL, "rb") as f:
            stored_docs = pickle.load(f)
    stored_docs[doc_id] = doc_text
    with open(config.DOCUMENT_PKL, "wb") as f:
        pickle.dump(stored_docs, f)


def get_document_list():
    stored_docs = {}
    if os.path.exists(config.DOCUMENT_PKL):
        with open(config.DOCUMENT_PKL, "rb") as f:
            stored_docs = pickle.load(f)
    return [
        {"id": doc_id, "text": doc_text} for doc_id, doc_text in stored_docs.items()
    ]


def format_node(node):
    return {
        "doc_id": str(node.id_),
        "text": str(node.text),
        "similarity": round(node.score, 2),
    }


def format_response(text, sources):
    return {"text": text, "sources": sources}
